﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FreedomERP.Dao.Inv;
using FreedomERP.Models;
using FreedomERP.Comm;
using FreedomERP.Dao.Inv.Impl;
using FreedomERP.Models.Inv;
using FreedomERP.Comm.Utils;
using FreedomERP.Dao.Bd.Impl;
using FreedomERP.Dao.Bd;
using FreedomERP.Services.Bd;
using FreedomERP.Services.Bd.Impl;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace FreedomERP.Services.Inv.Impl
{
    /// <summary>
    /// 欠货单管理业务层实现类
    /// 作者：陈新杰
    /// </summary>
    public class InvShortageOrderServiceImpl : IInvShortageOrderService
    {
        IInvShortageOrderDAO shortageOrderDAO = new InvShortageOrderDAOImpl();
        /// <summary>
        /// 根据条件获取欠货单列表
        /// </summary>
        /// <param name="paggingParams"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<InvShortageOrderView> QueryInvShortageOrderPaggingByParam(PagingParams paggingParams, out int totalCount)
        {
            List<InvShortageOrderView> resultList = new List<InvShortageOrderView>();
            DAOResult<InvShortageOrder> daoResult = shortageOrderDAO.QueryShortageOrderPaggingByParam(paggingParams, out totalCount);
            if (!daoResult.result)
            {
                throw new Exception(daoResult.msg);
            }
            else
            {
                List<InvShortageOrder> resultSet = daoResult.resultSet;
                foreach (var order in resultSet)
                {
                    InvShortageOrderView orderView = new InvShortageOrderView();
                    orderView.FBillDate = DateUtils.FormatDate(order.FBillDate, "yyyy-MM-dd");
                    orderView.FId = order.FId;
                    orderView.FNumber = order.FNumber;
                    orderView.FRemark = order.FRemark;
                    if (order.InvSendOrder != null)
                    {
                        orderView.FSendOrderNumber = order.InvSendOrder.FNumber;
                    }
                    if (order.BdCustomer != null)
                    {
                        orderView.FCustomerNumber = order.BdCustomer.FNumber;
                        orderView.FCustomerName = order.BdCustomer.FName;
                    }
                    orderView.FStatus = order.BdCategory.FName;
                    resultList.Add(orderView);
                }
            }
            return resultList;
        }


        /// <summary>
        /// 关闭欠货单，即将欠货单的状态标为“已核销”
        /// </summary>
        /// <param name="fId"></param>
        /// <param name="modifierId"></param>
        public void closeShortageOrder(String fId, String modifierId)
        {
            String statusId = null;
            int totalCount = 0;
            IBdCategoryService categeoryService = new BdCategoryServiceImpl();
            List<BdCategory> status = categeoryService.findInvShortageOrderStatusCategories(ConstData.CATEGORY_INV_SHORTAGE_STATUS_INVALID, 0, 1, out totalCount);
            if (status.Count <= 0)
                throw new Exception("欠货单状态不存在，无法修改状态");
            else
                statusId = status.First().FId;
            IInvShortageOrderDAO shortageOrdDao = new InvShortageOrderDAOImpl();
            shortageOrdDao.updateShortageOrderStatus(fId, modifierId, statusId);
        }


        /// <summary>
        /// 根据条件获取欠货单详情列表
        /// </summary>
        /// <param name="paggingParams"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<InvShortageOrderDetailView> QueryInvShortageOrderDetailPaggingByParam(PagingParams paggingParams, out int totalCount)
        {
            DAOResult<InvShortageOrderDetail> daoResult = shortageOrderDAO.QueryShortageOrderDetailPaggingByParam(paggingParams, out totalCount);
            if (!daoResult.result)
            {
                throw new Exception(daoResult.msg);
            }
            List<InvShortageOrderDetailView> shortageDetailViews = new List<InvShortageOrderDetailView>();
            foreach (var detail in daoResult.resultSet)
            {
                InvShortageOrderDetailView detailView = new InvShortageOrderDetailView();
                detailView.FId = detail.FId;
                detailView.FParentId = detail.FParentId;
                InvShortageOrder shortageOrder = detail.InvShortageOrder;
                if (shortageOrder != null)
                {
                    detailView.FParentNumber = shortageOrder.FNumber;
                }
                BdProduct bdProduct = detail.BdProduct;
                if (bdProduct != null)
                {
                    detailView.FProductId = bdProduct.FId;
                    detailView.FProductName = bdProduct.FName;
                    detailView.FProductNumber = bdProduct.FNumber;
                }
                detailView.FRemark = detail.FRemark;
                detailView.FShortageNumber = detail.FNumber.ToString();
                detailView.FReturnNumber = detail.FReturnNumber.ToString();
                BdCategory statusCate = detail.InvShortageOrder.BdCategory;
                if (statusCate != null)
                {
                    detailView.FStatus = statusCate.FName;
                }
                shortageDetailViews.Add(detailView);

            }
            return shortageDetailViews;

        }

        /// <summary>
        /// 修改欠货单详情
        /// </summary>
        /// <param name="fId"></param>
        /// <param name="fParentId"></param>
        /// <param name="returnNum"></param>
        /// <param name="modifierId"></param>
        /// <returns></returns>
        public String UpdateShortageOrderDetail(String fId, String fParentId, String returnNum, String modifierId)
        {
            String fid = null;
            DAOResult<String> daoResult = shortageOrderDAO.UpdateShortageOrderDetail(fId, fParentId, returnNum, modifierId);
            if (!daoResult.result)
            {
                throw new Exception(daoResult.msg);
            }
            else
            {
                fid = daoResult.resultSet.First();

            }
            return fid;

        }

       

        /// <summary>
        /// 导出缺货单信息到excel
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public void ExportShortageOrderToExcel(String FId, string serverPath, HttpResponseBase response)
        {
            InvShortageOrder shortageOrder = shortageOrderDAO.GetShortageOrderByFId(FId);

            if (shortageOrder != null)
            {
                string templateFilePath = @"" + serverPath + "Upload\\Template\\ShortageOrderExportTemplate.xls";
                FileStream file = new FileStream(templateFilePath, FileMode.Open, FileAccess.Read);

                MemoryStream ms = new MemoryStream();

                HSSFWorkbook workbook = new HSSFWorkbook(file);
                HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0);

                HSSFCellStyle style = (HSSFCellStyle)workbook.CreateCellStyle();
                style.BorderBottom = BorderStyle.THIN;
                style.BorderLeft = BorderStyle.THIN;
                style.BorderRight = BorderStyle.THIN;
                style.BorderTop = BorderStyle.THIN;

                if (shortageOrder.BdCustomer != null)
                {
                    HSSFCell customerCell = (HSSFCell)sheet.GetRow(3).CreateCell(1);
                    customerCell.SetCellValue(shortageOrder.BdCustomer.FName);
                }

                if (shortageOrder.FBillDate != null)
                {
                    HSSFCell billDateCell = (HSSFCell)sheet.GetRow(3).CreateCell(3);
                    billDateCell.SetCellValue(DateUtils.FormatDate(shortageOrder.FBillDate, "yyyy-MM-dd"));
                }

                if (shortageOrder.InvShortageOrderDetail != null)
                {
                    int r = 5;
                    long numberCount = 0L;
                    foreach (InvShortageOrderDetail shortageOrderDetail in shortageOrder.InvShortageOrderDetail)
                    {
                        BdProduct product = shortageOrderDetail.BdProduct;

                        HSSFRow row = (HSSFRow)sheet.CreateRow(r);

                        if (product != null)
                        {
                            HSSFCell codeCell = (HSSFCell)row.CreateCell(0);
                            codeCell.SetCellValue(product.FNumber);
                            codeCell.CellStyle = style;

                            HSSFCell nameCell = (HSSFCell)row.CreateCell(1);
                            nameCell.SetCellValue(product.FName);
                            nameCell.CellStyle = style;
                        }

                        HSSFCell numberCell = (HSSFCell)row.CreateCell(2);
                        numberCell.SetCellValue(shortageOrderDetail.FNumber);
                        numberCell.CellStyle = style;

                        HSSFCell remarkCell = (HSSFCell)row.CreateCell(3);
                        remarkCell.SetCellValue(shortageOrderDetail.FRemark);
                        remarkCell.CellStyle = style;

                        numberCount += shortageOrderDetail.FNumber;
                        r++;
                    }

                    HSSFRow rowCount = (HSSFRow)sheet.CreateRow(r);
                    for (int rt = 0; rt < 4; rt++)
                    {
                        HSSFCell countCell = (HSSFCell)rowCount.CreateCell(rt);
                        countCell.CellStyle = style;

                        if (rt == 0)
                        {
                            countCell.SetCellValue("合计：");
                        }
                        else if (rt == 2)
                        {
                            countCell.SetCellValue(numberCount);
                        }
                    }

                }

                workbook.Write(ms);
                response.AddHeader("Content-Disposition", string.Format("attachment; filename=ShortageOrder_" + shortageOrder.FNumber + ".xls"));
                response.BinaryWrite(ms.ToArray());
                workbook = null;
                ms.Close();
                ms.Dispose();
            }
        }
    }
}